import wsgiref.handlers

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.api import users

import base
import base_page
import data
import msg

# Display pending approval requests and approve/decline requests
class ApproveHandler(base_page.BaseHandler):
  def PreCheckOrRedirect(self):
    if not (self.user.is_sys_admin or \
            self.user.is_donor_mod or \
            self.user.is_manufacturer_mod):
      self.RedirectAndRaise("/")

  def SetAppTypeNames(self, apps):
    modified_apps = []
    # add the name for each type
    for app in apps:
      app.type_str = msg.Get(data.GetUserLevelApplicationTypeStr(app.type))
      modified_apps.append(app)
    return modified_apps

  def ProcessGet(self):
    self.Setup('approvals.html',
                required_registered=True,
                show_search_box=False)
    list_type = self.request.get('list')
    if not list_type: list_type = 'pending'
    if list_type == 'pending':
      user_filter = data.UserLevelApplication.PENDING
      donor_filter = data.DonorProfile.PENDING
      manufacturer_filter = data.ManufacturerProfile.PENDING
      self.template_values['show_pending'] = True
    elif list_type == 'approved':
      user_filter = data.UserLevelApplication.APPROVED
      donor_filter = data.DonorProfile.ACTIVE
      manufacturer_filter = data.ManufacturerProfile.ACTIVE
      self.template_values['show_approved'] = True
    elif list_type == 'denied':
      user_filter = data.UserLevelApplication.DENIED
      donor_filter = data.DonorProfile.DELETED
      manufacturer_filter = data.ManufacturerProfile.DELETED
      self.template_values['show_denied'] = True
    # Get user approvals
    if self.user.is_sys_admin:
      q = data.UserLevelApplication().all()
      res = q.filter('state =', user_filter).order('date')
      modified_apps = self.SetAppTypeNames(res)
      self.template_values['user_approvals'] = modified_apps 
    # Get donor profiles
    if self.user.is_sys_admin or self.user.is_donor_mod:
      q = data.DonorProfile().all()
      res = q.filter('state =', donor_filter).order('date')
      self.template_values['donor_profiles'] = [ x for x in res ]
    # Get manufacturer profiles
    if self.user.is_sys_admin or self.user.is_manufacturer_mod:
      q = data.ManufacturerProfile().all()
      res = q.filter('state =', manufacturer_filter).order('date')
      self.template_values['manufacturer_profiles'] = [x for x in res ]
    self.Render()

  def ProcessPost(self):
    self.Setup('approvals.html',
                required_registered=True,
                show_search_box=False)
    type = self.GetFieldOrRedirect('type')
    if type == 'user':
      self.ProcessUserApprovals()
    elif type == 'donor':
      self.ProcessDonorApprovals()
    elif type == 'manufacturer':
      self.ProcessManufacturerApprovals()
    else:
      self.redirect("/")

  def ProcessDonorApprovals(self):
    if not (self.user.is_sys_admin or self.user.is_donor_mod):
      self.RedirectAndRaise("/")
    profile = self.GetEntityByKeyName("profileid")
    if not profile:
      self.RedirectAndRaise("/")
    if self.request.get('approve'):
      profile.state = data.DonorProfile.ACTIVE
    elif self.request.get('deny'):
      profile.state = data.DonorProfile.DELETED
    else:
      self.RedirectAndRaise("/")
    profile.put()
    self.redirect("/approvals")
   
  def ProcessManufacturerApprovals(self):
    if not (self.user.is_sys_admin or self.user.is_donor_mod):
      self.RedirectAndRaise("/")
    profile = self.GetEntityByKeyName("profileid")
    if not profile:
      self.RedirectAndRaise("/")
    if self.request.get('approve'):
      profile.state = data.ManufacturerProfile.ACTIVE
    elif self.request.get('deny'):
      profile.state = data.ManufacturerProfile.DELETED
    else:
      self.RedirectAndRaise("/")
    profile.put()
    self.redirect("/approvals")

  def SetUserLevel(self, creator, user_type, value):
    if user_type == data.UserLevelApplication.SYS_ADMIN:
      creator.is_sys_admin = value
    elif user_type == data.UserLevelApplication.REQUEST_MOD:
      creator.is_request_mod = value
    elif user_type == data.UserLevelApplication.DONOR_MOD:
      creator.is_donor_mod = value
    elif user_type == data.UserLevelApplication.MANUFACTURER_MOD:
      creator.is_manufacturer_mod = value
    else:
      self.RedirectAndRaise("/")
    creator.put()

  def ProcessUserApprovals(self):
    if not self.user.is_sys_admin:
      self.RedirectAndRaise("/")
    app = self.GetEntityByKeyName("appid")
    if not app: self.RedirectAndRaise("/approvals")
    if self.request.get('approve'):
      app.state = data.UserLevelApplication.APPROVED
      self.SetUserLevel(app.creator, app.type, True) 
      app.put()
    elif self.request.get('deny'):
      app.state = data.UserLevelApplication.DENIED
      app.put()
    self.RedirectAndRaise("/approvals")
